﻿using Newtonsoft.Json;
using System;
using System.Linq;
using System.Web;
using System.Web.Http;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Model.ViewModel.Sellers;
using ZBJF.Warranty.WebApiSite.Filter;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Common.Enums.InsuranceOrder;
using ZBJF.Warranty.Common.Enums.Data;
using System.Collections.Generic;
using ZBJF.Warranty.TheThirdPartyInteraction.Sellers;
using ZBJF.Warranty.TheThirdPartyInteraction.Sellers.ChiDu.Model.Response;
using ZBJF.Warranty.TheThirdPartyInteraction.Sellers.ChiDu.Model.Request;
using ZBJF.Warranty.TheThirdPartyInteraction.Sellers.ChiDu;
using ZBJF.Warranty.Model.ViewModel.InsuranceProducts;
using ZBJF.Warranty.TheThirdPartyInteraction.InsuranceCompany.HuaAn;
using ZBJF.Warranty.TheThirdPartyInteraction.InsuranceCompany.HuaAn.Model.Response;
using ZBJF.Warranty.TheThirdPartyInteraction.InsuranceCompany.HuaAn.Model;
using System.Transactions;
using ZBJF.Warranty.Model.ViewModel.Product;
using ZBJF.Warranty.Model.ViewModel.Order;
using ZBJF.Warranty.Common.Enums.Base;

namespace ZBJF.Warranty.WebApiSite.Controllers
{
    [SellerAuthentication]
    public class ChiDuSellerController : ApiController
    {
        // 身份票据 （账号|Md5(密码)）
        private readonly string ticketName = "ticket";
        //锁对象
        private static readonly object obj = new object();

        #region 获取产品可承保型号和品牌、价格区间 + ResultObject<SellerInsuranceProductsAvailableInfo> GetAvailableInfo(AvailableBrandAndModelParam param)
        /// <summary>
        /// 获取产品可承保型号和品牌、价格区间
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultObject<SellerInsuranceProductsAvailableInfo> GetAvailableInfo(AvailableBrandAndModelParam param)
        {
            ResultObject<SellerInsuranceProductsAvailableInfo> result = new ResultObject<SellerInsuranceProductsAvailableInfo>()
            {
                Result = true,
                StatusCode = StatusCodeEnum.ParameterError,
                Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.ParameterError),
            };
            if (param == null || string.IsNullOrEmpty(param.SellerInsuranceProductsCode))
                return result;

            try
            {
                string sellerCode = GetSellerCode();
                SellerInsuranceProductsAvailableInfo info = ServiceFactory.SellerInsuranceProductsServiceInstance.GetAvailableInfo(sellerCode, param.SellerInsuranceProductsCode);

                result.Result = true;
                result.StatusCode = StatusCodeEnum.Success;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.Success);
                result.Data = info;
                return result;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("获取产品可承保型号和品牌异常、价格区间;param:" + JsonConvert.SerializeObject(param) + "；\r\n" + ex.ToString(), LogType.error);
                result.StatusCode = StatusCodeEnum.Error;
                result.Message = "获取失败！";
                return result;
            }
        }
        #endregion

        #region 提交核保信息 + ResultObject<string> AddInsuranceOrderInfo(InsuranceOrderInfoParam param)
        /// <summary>
        /// 提交保单信息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultObject<string> AddInsuranceOrderInfo(InsuranceOrderInfoParam param)
        {
            LogHelper.WriteLog("收到尺度提交保单信息：" + JsonConvert.SerializeObject(param), LogType.tag);
            ResultObject<string> result = new ResultObject<string>()
            {
                Result = true,
                StatusCode = StatusCodeEnum.ParameterError,
                Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.ParameterError),
            };
            //验证参数
            if (param == null
                || string.IsNullOrEmpty(param.SellerBusinessNo)
                || string.IsNullOrEmpty(param.SellerInsuranceProductsCode)
                || string.IsNullOrEmpty(param.SaleEmployeeId)
                || string.IsNullOrEmpty(param.UserName)
                || string.IsNullOrEmpty(param.UserPhone)
                || param.CertificateType < 1
                || param.CertificateType > 4
                || string.IsNullOrEmpty(param.CertificateNO)
                || string.IsNullOrEmpty(param.IMEI)
                || param.IMEI.Length != 15
                || param.ModelId < 1
                || string.IsNullOrEmpty(param.CertificateImageUrl)
                || param.Timestamp < 1
                || string.IsNullOrEmpty(param.Sign)
                )
                return result;

            string sellerCode = GetSellerCode();//销售商编码
            DateTime nowTime = DateTime.Now;

            //验证时间戳,防止重复提交
            result = ValidateCode<string>(sellerCode + "AddInsuranceOrderInfo", param.Timestamp);
            if (result.StatusCode != StatusCodeEnum.Success)
                return result;

            //获取销售商信息
            Sellers sellerInfo = ServiceFactory.SellersServiceInstance.LoadBySellerCode(sellerCode);

            //验证信息是否被篡改
            if (!ChiDuHelper.ValidateMessage(param, sellerInfo.SellerSecretKey))
            {
                result.StatusCode = StatusCodeEnum.MessageValidateError;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.MessageValidateError);
                return result;
            }
            //获取销售商产品ID 、 销售商产品承保公司、承保子公司、承保子公司ID
            SellerInsuranceProductsInfo sellerInsuranceProductsInfo = ServiceFactory.SellerInsuranceProductsServiceInstance.GetSellerInsuranceProductsId(param.SellerInsuranceProductsCode);
            if (sellerInsuranceProductsInfo == null || sellerInsuranceProductsInfo.SellerInsuranceProductsID < 1)
            {
                result.StatusCode = StatusCodeEnum.MessageValidateError;
                result.Message = "未获取到销售商产品信息";
                LogHelper.WriteLog("处理尺度提交保单信息__未获取到销售商产品信息：销售商产品编码：" + param.SellerInsuranceProductsCode, LogType.remark);
                return result;
            }
            long sellerInsuranceProductsId = sellerInsuranceProductsInfo.SellerInsuranceProductsID;

            //验证是否符合购买条件
            string message = "";
            bool accept = ServiceFactory.SellerInsuranceProductsServiceInstance.VerifyAcceptable(sellerCode, sellerInsuranceProductsId, param.ModelId, 0, 0, out message);

            //获取保险产品信息
            CellPhoneServiceProductInfo insuranceProduct = ServiceFactory.InsuranceProductsServiceInstance.GetInsuranceProductsInfo(sellerInsuranceProductsId);
            if (insuranceProduct == null || insuranceProduct.ID < 1)
            {
                result.StatusCode = StatusCodeEnum.MessageValidateError;
                result.Message = "未获取到保险产品信息";
                LogHelper.WriteLog("处理尺度提交保单信息__未获取到保险产品信息：SellerInsuranceProductsId：" + sellerInsuranceProductsId, LogType.remark);
                return result;
            }

            //保险产品服务项目信息——尺度只有一个手机维修服务项目
            CellPhoneServiceProject cellPhoneServiceProjectInfo = ServiceFactory.CellPhoneServiceProjectServiceInstance.LoadEntities(t => t.InsuranceProductsID == insuranceProduct.ID).FirstOrDefault();
            if (cellPhoneServiceProjectInfo == null || cellPhoneServiceProjectInfo.ID < 1)
            {
                result.StatusCode = StatusCodeEnum.MessageValidateError;
                result.Message = "未获取到保险产品服务项目信息";
                LogHelper.WriteLog("处理尺度提交保单信息__未获取到保险产品服务项目信息：InsuranceProductsID：" + insuranceProduct.ID, LogType.remark);
                return result;
            }


            //获取投保型号信息和品牌信息
            EquipmentInfo equipmentInfo = ServiceFactory.ProductModelsServiceInstance.GetEquipmentInfo(param.ModelId);
            if (equipmentInfo == null || equipmentInfo.ModelId < 1)
            {
                result.StatusCode = StatusCodeEnum.MessageValidateError;
                result.Message = "未获取到设备信息";
                LogHelper.WriteLog("处理尺度提交保单信息__未获取到设备信息：型号ID：" + param.ModelId, LogType.remark);
                return result;
            }

            bool isOK = false;
            //byte userCertificateType = param.CertificateType;  //证件类型
            byte orderStatus = (byte)InsuranceOrderStatus.Create;
            long insuranceOrderId = 0;
            long insuranceServiceProjectId = 0;
            string createBy = "福建尺度";
            string IDFV = "";
            //锁，防止快速重复提交
            InsuranceOrder insuranceOrderModel;
            lock (obj)
            {
                #region 保存投保订单信息
                //检查数据库是否已经存在此订单信息
                insuranceOrderModel = ServiceFactory.InsuranceOrderServiceInstance.LoadBySellerBusinessNo(param.SellerBusinessNo, sellerInfo.ID);
                if (!accept) //不符合购买条件的自动审核不通过
                {
                    orderStatus = (byte)InsuranceOrderStatus.ApprovedButNotPassed;
                }
                if (insuranceOrderModel != null && insuranceOrderModel.ID > 0)
                {
                    #region 修改
                    InsuranceOrderStatus status = (InsuranceOrderStatus)insuranceOrderModel.OrderStatus;
                    //判断订单状态
                    if (status == InsuranceOrderStatus.Cancel
                        || status == InsuranceOrderStatus.Create
                        || status == InsuranceOrderStatus.ApprovedButNotPassed)
                    {
                        //修改订单，且重置订单状态为待审核 
                        using (TransactionScope sc = new TransactionScope())
                        {
                            try
                            {
                                isOK = UpdateInsuranceOrderInfo(insuranceOrderModel, orderStatus, sellerInsuranceProductsId, param, insuranceProduct, sellerInsuranceProductsInfo, createBy, nowTime);
                                insuranceOrderId = insuranceOrderModel.ID;
                                //修改服务项目信息 —— 尺度默认只有一个手机维修服务项目
                                if (isOK)
                                {
                                    insuranceServiceProjectId = UpdateServiceProject(insuranceOrderId, param.IMEI, IDFV, insuranceProduct, cellPhoneServiceProjectInfo, equipmentInfo);
                                    if (insuranceServiceProjectId<1)
                                    {
                                        LogHelper.WriteLog("更新保单信息服务项目失败", LogType.remark);
                                        sc.Dispose();
                                        isOK = false;
                                    }
                                }
                                sc.Complete();
                            }
                            catch (Exception ex)
                            {
                                LogHelper.WriteLog("更新保单信息异常" + ex.ToString(), LogType.error);
                                sc.Dispose();
                                isOK = false;
                            }
                        }
                    }
                    else
                    {
                        result.StatusCode = StatusCodeEnum.OrderRepeat;
                        result.Message = "已存在审核通过后的订单信息";
                        LogHelper.WriteLog("处理尺度提交保单信息__第三方订单号在数据库中已存在的审核通过后的订单：第三方订单号：" + param.SellerBusinessNo, LogType.remark);
                        return result;
                    }
                    #endregion
                }
                else
                {
                    #region 新增
                    //检查数据库是否已经存在此设备IMEI信息
                    List<CellPhoneInsuranceInfoModel> insuranceOrderList = ServiceFactory.CellPhoneInsuranceInfoServiceInstance.LoadByIMEI(param.IMEI, sellerInsuranceProductsInfo.CompanyID);
                    if (insuranceOrderList != null && insuranceOrderList.Count() > 0)
                    {
                        //1、判断是否有审核通过或者已生效状态下的订单
                        if (insuranceOrderList.Where(t => t.OrderStatus == (byte)InsuranceOrderStatus.HadEffective || t.OrderStatus == (byte)InsuranceOrderStatus.ApprovedAndPassed).Any())
                        {
                            result.StatusCode = StatusCodeEnum.OrderRepeat;
                            result.Message = "已存在审核通过后的设备IMEI信息";
                            LogHelper.WriteLog("处理尺度提交保单信息__第三方订单号在数据库中已存在审核通过后的设备IMEI信息：设备IMEI：" + param.IMEI, LogType.remark);
                            return result;
                        }
                        else
                        {
                            //2、是否有待审核、审核未通过、取消/退保的订单
                            CellPhoneInsuranceInfoModel  m= insuranceOrderList.Where(t => t.OrderStatus == (byte)InsuranceOrderStatus.Cancel || t.OrderStatus == (byte)InsuranceOrderStatus.Create || t.OrderStatus == (byte)InsuranceOrderStatus.ApprovedButNotPassed).FirstOrDefault();
                            if (m != null)
                            {
                                insuranceOrderModel = ServiceFactory.InsuranceOrderServiceInstance.LoadByID(m.InsuranceOrderID);
                                //修改订单，且重置订单状态为待审核 
                                using (TransactionScope sc = new TransactionScope())
                                {
                                    try
                                    {
                                        isOK = UpdateInsuranceOrderInfo(insuranceOrderModel, orderStatus, sellerInsuranceProductsId, param, insuranceProduct, sellerInsuranceProductsInfo, createBy, nowTime);
                                        insuranceOrderId = insuranceOrderModel.ID;

                                        //修改服务项目信息 —— 尺度默认只有一个手机维修服务项目
                                        if (isOK)
                                        {
                                            insuranceServiceProjectId = UpdateServiceProject(insuranceOrderId, param.IMEI, IDFV, insuranceProduct, cellPhoneServiceProjectInfo, equipmentInfo);
                                            if (insuranceServiceProjectId<1)
                                            {
                                                LogHelper.WriteLog("更新保单信息服务项目失败", LogType.remark);
                                                sc.Dispose();
                                                isOK = false;
                                            }
                                        }
                                        sc.Complete();
                                    }
                                    catch (Exception ex)
                                    {
                                        LogHelper.WriteLog("更新保单信息异常" + ex.ToString(), LogType.error);
                                        sc.Dispose();
                                        isOK = false;
                                    }
                                }

                            }
                            else
                            {
                                using (TransactionScope sc = new TransactionScope())
                                {
                                    try
                                    {
                                        insuranceOrderId = AddInsuranceOrder(orderStatus, createBy, param, sellerInsuranceProductsInfo, insuranceProduct, equipmentInfo, sellerInfo, nowTime);// 
                                        isOK = insuranceOrderId > 0;
                                        //新增服务项目信息 —— 尺度默认只有一个手机维修服务项目
                                        if (isOK)
                                        {
                                            insuranceServiceProjectId = AddServiceProject(insuranceOrderId, param.IMEI, IDFV, insuranceProduct, cellPhoneServiceProjectInfo, equipmentInfo);
                                            if (insuranceServiceProjectId < 1)
                                            {
                                                LogHelper.WriteLog("更新保单信息服务项目失败", LogType.remark);
                                                sc.Dispose();
                                                isOK = false;
                                            }
                                        }
                                        sc.Complete();
                                    }
                                    catch (Exception ex)
                                    {
                                        LogHelper.WriteLog("新增保单信息异常" + ex.ToString(), LogType.error);
                                        sc.Dispose();
                                        isOK = false;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        using (TransactionScope sc = new TransactionScope())
                        {
                            try
                            {
                                insuranceOrderId = AddInsuranceOrder(orderStatus, createBy, param, sellerInsuranceProductsInfo, insuranceProduct, equipmentInfo, sellerInfo, nowTime);// 
                                isOK = insuranceOrderId > 0;
                                //新增服务项目信息 —— 尺度默认只有一个手机维修服务项目
                                if (isOK)
                                {
                                    insuranceServiceProjectId = AddServiceProject(insuranceOrderId, param.IMEI, IDFV, insuranceProduct, cellPhoneServiceProjectInfo, equipmentInfo);
                                    if (insuranceServiceProjectId < 1)
                                    {
                                        LogHelper.WriteLog("更新保单信息服务项目失败", LogType.remark);
                                        sc.Dispose();
                                        isOK = false;
                                    }
                                }
                                sc.Complete();
                            }
                            catch (Exception ex)
                            {
                                LogHelper.WriteLog("新增保单信息异常" + ex.ToString(), LogType.error);
                                sc.Dispose();
                                isOK = false;
                            }
                        }
                    }
                    #endregion
                }
                #endregion
            }
            //这里指表示尺度的数据提交成功，不代表审核信息
            if (isOK)
            {
                //获取图片
                ChiDuHelper.SaveImage(param.CertificateImageUrl, insuranceServiceProjectId, (byte)ServiceProductType.CellPhoneRepair);

                //审核不通过——调用尺度接口直接告诉他们审核结果
                if (!accept)
                {
                    ChiDuDataInteraction chidu = new ChiDuDataInteraction(sellerInfo.SellerInterfaceSecretKey, sellerInfo.SellerInterfaceUrl);
                    chidu.InvokeChiduCheckResultInterface(param.SellerBusinessNo, accept, "设备信息不符合购买条件");
                    //保存审核结果
                    //添加审核日志
                    InsuranceOrderCheckLog log = new InsuranceOrderCheckLog()
                    {
                        InsuranceOrderId = insuranceOrderId,
                        CheckRemark = "设备信息不符合购买条件",
                        CheckResult = false,
                        CheckTime = nowTime,
                        CheckUserAccount = "admin",
                        CheckUserName = "admin"
                    };
                    var insuranceOrderCheckLog = ServiceFactory.InsuranceOrderCheckLogServiceInstance.AddEntities(log);
                    if (insuranceOrderCheckLog.ID < 1)
                        LogHelper.WriteLog("处理尺度提交保单信息__添加审核日志失败：" + JsonConvert.SerializeObject(log), LogType.remark);
                }
                else
                {
                    ChiDuHelper.SendMessage(sellerInfo.SellersName, param.UserName, "10", Convert.ToInt32(insuranceOrderId));
                }
                result.StatusCode = StatusCodeEnum.Success;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.Success);
                return result;
            }
            else
            {
                result.StatusCode = StatusCodeEnum.Error;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.Error);
                LogHelper.WriteLog("处理尺度提交保单信息__保存投保订单信息：" + JsonConvert.SerializeObject(insuranceOrderModel), LogType.remark);
                return result;
            }
        }
        #endregion

        #region 保单审核状态查询 + ResultObject<OrderQueryResult> OrderQuery(string ThirdUniqueNumber)
        [HttpGet]
        public ResultObject<OrderQueryResult> OrderQuery(string SellerBusinessNo)
        {
            ResultObject<OrderQueryResult> result = new ResultObject<OrderQueryResult>()
            {
                Result = true,
                StatusCode = StatusCodeEnum.ParameterError,
                Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.ParameterError),
            };
            if (string.IsNullOrEmpty(SellerBusinessNo))
                return result;
            string sellerCode = GetSellerCode();//销售商编码

            //获取销售商信息
            Sellers sellerInfo = ServiceFactory.SellersServiceInstance.LoadBySellerCode(sellerCode);
            //查询保单审核信息
            InsuranceOrder orderInfo = ServiceFactory.InsuranceOrderServiceInstance.LoadBySellerBusinessNo(SellerBusinessNo, sellerInfo.ID);
            if (orderInfo == null || orderInfo.ID < 1)
            {
                result.StatusCode = StatusCodeEnum.OrderNoFound;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.OrderNoFound);
                return result;
            }

            string remark = "";
            ChiDuResultEnum checkResult;
            InsuranceOrderStatus orderStatus = (InsuranceOrderStatus)orderInfo.OrderStatus;
            //审核不通过，获取审核不通过原因
            if (orderStatus == InsuranceOrderStatus.ApprovedButNotPassed)
            {
                var log = ServiceFactory.InsuranceOrderCheckLogServiceInstance.LoadByInsuranceOrderCheckLogId((int)orderInfo.ID).OrderByDescending(t => t.ID).FirstOrDefault();
                if (log != null)
                    remark = log.CheckRemark;
                checkResult = ChiDuResultEnum.nopass;
            }
            else if (orderStatus == InsuranceOrderStatus.ApprovedAndPassed)
            {
                checkResult = ChiDuResultEnum.pass;
            }
            else if (orderStatus == InsuranceOrderStatus.Create)
            {
                checkResult = ChiDuResultEnum.nocheck;
            }
            else
            {
                checkResult = ChiDuResultEnum.unknown;
            }

            result.StatusCode = StatusCodeEnum.Success;
            result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.Success);
            result.Data = new OrderQueryResult()
            {
                Content = new ChiDuDataInteraction(sellerInfo.SellerInterfaceSecretKey).GetCheckResult(SellerBusinessNo, checkResult, remark)
            };
            return result;

        }
        #endregion

        #region 用户购买保险成功-提交保单信息 + ResultObject<string> BuyResultNotice(BuyResultNoticeParam param)
        /// <summary>
        /// 用户购买保险成功-提交保单信息
        ///华安测试环境数据： 保单号H10104P08490220181591013，订单号itest_null_20180409142816379
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultObject<string> BuyResultNotice(BuyResultNoticeParam param)
        {
            ResultObject<string> result = new ResultObject<string>()
            {
                Result = true,
                StatusCode = StatusCodeEnum.ParameterError,
                Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.ParameterError),
            };
            if (param == null || string.IsNullOrEmpty(param.SellerBusinessNo) || string.IsNullOrEmpty(param.ThirdOrderNO))
                return result;

            string sellerCode = GetSellerCode();//销售商编码

            // 验证时间戳,防止重复提交
            result = ValidateCode<string>(sellerCode + "BuyResultNotice", param.Timestamp);
            if (result.StatusCode != StatusCodeEnum.Success)
                return result;

            DateTime nowTime = DateTime.Now;
            //获取销售商信息
            Sellers sellerInfo = ServiceFactory.SellersServiceInstance.LoadBySellerCode(sellerCode);
            //验证信息是否被篡改
            if (!ChiDuHelper.ValidateBuyResultNoticeParam(param, sellerInfo.SellerSecretKey))
            {
                result.StatusCode = StatusCodeEnum.MessageValidateError;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.MessageValidateError);
                return result;
            }

            //获取本地订单信息
            InsuranceOrder insuranceOrderModel = ServiceFactory.InsuranceOrderServiceInstance.LoadBySellerBusinessNo(param.SellerBusinessNo, sellerInfo.ID);
            //IMEI信息
            string IMEI = ServiceFactory.CellPhoneInsuranceInfoServiceInstance.GetIMEIOrIDFV(insuranceOrderModel.ID);
            if (insuranceOrderModel == null || !insuranceOrderModel.SellerInsuranceProductID.HasValue)
            {
                result.StatusCode = StatusCodeEnum.OrderNoFound;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.OrderNoFound);
                LogHelper.WriteLog("未获取到本地保单信息:尺度订单号：" + param.SellerBusinessNo + "；销售商ID:" + sellerInfo.ID, LogType.remark);
                return result;
            }
            if (insuranceOrderModel.OrderStatus != (byte)InsuranceOrderStatus.ApprovedAndPassed)
            {
                result.StatusCode = StatusCodeEnum.OrderStatusError;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.OrderStatusError);
                LogHelper.WriteLog("本地订单信息状态不是审核通过状态:尺度订单号：" + param.SellerBusinessNo + "；销售商ID:" + sellerInfo.ID, LogType.remark);
                return result;
            }

            //调用华安接口验证保单的真实性
            //获取华安保单信息
            HuaAnBaseModel<HuaAnInsuranceOrderInfo> huaAnOrderInfo = HuaAnHelper.QueryInsuranceOrderInfo(param.SellerBusinessNo, param.ThirdOrderNO);
            if (huaAnOrderInfo == null || huaAnOrderInfo.errCode != 0 || huaAnOrderInfo.data == null)
            {
                result.StatusCode = StatusCodeEnum.HuaAnOrderNoFound;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.HuaAnOrderNoFound);
                LogHelper.WriteLog("未获取到华安保单信息或状态不对:" + JsonConvert.SerializeObject(huaAnOrderInfo), LogType.remark);
                return result;
            }
            //状态是否是承保状态
            if (huaAnOrderInfo.data.policy.status != "5")
            {
                result.StatusCode = StatusCodeEnum.HuaAnOrderNoFound;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.HuaAnOrderNoFound);
                LogHelper.WriteLog("华安保单信息状态不对:" + JsonConvert.SerializeObject(huaAnOrderInfo), LogType.remark);
                return result;
            }

            byte idcardType = HuaAnHelper.ConvertCertificateType(huaAnOrderInfo.data.policy.idcardType);
            //本地订单信息与华安信息核对：IMEI、证件类型、证件号码
            if (huaAnOrderInfo.data.policy.imei != IMEI ||
               idcardType != insuranceOrderModel.CertificateType ||
               huaAnOrderInfo.data.policy.idcardNo != insuranceOrderModel.CertificateNO)
            {
                result.StatusCode = StatusCodeEnum.HuaAnOrderInfoValidateError;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.HuaAnOrderInfoValidateError);
                LogHelper.WriteLog(string.Format("本地订单信息与华安信息核对失败：本地信息:{0}-{1}-{2}；华安信息:{3}-{4}-{5}；订单号：{6}；保单号：{7}；", IMEI, insuranceOrderModel.CertificateType, insuranceOrderModel.CertificateNO, huaAnOrderInfo.data.policy.imei, huaAnOrderInfo.data.policy.idcardType, huaAnOrderInfo.data.policy.idcardNo, param.SellerBusinessNo, param.ThirdOrderNO), LogType.remark);
                return result;
            }


            //获取保险产品信息
            CellPhoneServiceProductInfo insuranceProduct = ServiceFactory.InsuranceProductsServiceInstance.GetInsuranceProductsInfo(insuranceOrderModel.SellerInsuranceProductID.Value);
            insuranceOrderModel.ThirdOrderNO = param.ThirdOrderNO;
            insuranceOrderModel.ThirdUniqueNumber = huaAnOrderInfo.data.policy.policyAppNo;
            insuranceOrderModel.OrderStatus = (byte)InsuranceOrderStatus.HadEffective;
            insuranceOrderModel.ServiceStartTime = CommonMethod.GetServiceStartTime(nowTime, insuranceProduct.WaitDays); //服务开始时间:核保成功时间+生效等待期
            insuranceOrderModel.ServiceEndTime = CommonMethod.GetServiceEndTime(insuranceOrderModel.ServiceStartTime.Value, insuranceProduct.PolicyPeriodYear, insuranceProduct.PolicyPeriodMonth, insuranceProduct.PolicyPeriodDay); //服务结束时间： 服务开始时间+承保日期

            bool re = ServiceFactory.InsuranceOrderServiceInstance.UpdateEntities(insuranceOrderModel);
            if (!re)
            {
                result.StatusCode = StatusCodeEnum.Error;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.Error);
                LogHelper.WriteLog("本地更新保单信息失败：" + JsonConvert.SerializeObject(insuranceOrderModel), LogType.remark);
                return result;
            }


            result.StatusCode = StatusCodeEnum.Success;
            result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.Success);
            return result;
        }
        #endregion

        #region 验证时间戳是否合法 + ResultObject<T> ValidateCode<T>(string sessionName,long chiduTimestamp)
        /// <summary>
        /// 验证时间戳是否合法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sessionName">Session缓存名称</param>
        /// <param name="chiduTimestamp"></param>
        /// <returns></returns>
        private ResultObject<T> ValidateCode<T>(string sessionName, long chiduTimestamp)
        {
            ResultObject<T> result = new ResultObject<T>();
            result.Result = true;

            long beforeTimeStamp = 0;
            object timeStamp = HttpContext.Current.Session[sessionName];
            if (timeStamp != null)
                beforeTimeStamp = Convert.ToInt64(timeStamp);
            //当前时间戳小于或等于之前的时间戳。说明是重复的
            if (chiduTimestamp < beforeTimeStamp)
            {
                result.StatusCode = StatusCodeEnum.TimeStampError;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.TimeStampError);
                LogHelper.WriteLog(sessionName + "保单信息__时间戳不正确：尺度时间戳：" + chiduTimestamp + "；之前时间戳：" + beforeTimeStamp, LogType.remark);
                return result;
            }
            DateTime nowTime = DateTime.Now;
            //session可能会超时
            long nowTimeStamp = CommonMethod.GetTimeStamp(nowTime);
            if (nowTimeStamp - chiduTimestamp > 180000000)
            {
                result.StatusCode = StatusCodeEnum.TimeStampOver;
                result.Message = EnumHelper.Instance.GetDescription(typeof(StatusCodeEnum), StatusCodeEnum.TimeStampOver);
                LogHelper.WriteLog(sessionName + "保单信息-提交保单信息__时间戳超时：尺度时间戳：" + chiduTimestamp + "；本地时间戳：" + nowTimeStamp, LogType.remark);
                return result;
            }
            HttpContext.Current.Session.Add(sessionName, chiduTimestamp);

            result.StatusCode = StatusCodeEnum.Success;
            return result;
        }
        #endregion

        #region 获取销售商账户编码 + string GetSellerCode()
        /// <summary>
        /// 获取销售商账户编码
        /// </summary>
        /// <returns></returns>
        private string GetSellerCode()
        {
            var ticket = HttpContext.Current.Request.Headers.Get(ticketName);
            //由于在身份验证过滤器中已经验证过一次。所以这里不需要再做验证了
            return ticket.Split('|')[0];
        }
        #endregion


        #region 新增保单 
        /// <summary>
        /// 新增保单
        /// </summary>
        /// <param name="orderStatus">订单状态</param>
        /// <param name="createBy">创建人</param>
        /// <param name="param">尺度参数</param>
        /// <param name="sellerInsuranceProductsInfo">销售商商品信息</param>
        /// <param name="insuranceProduct">保险产品信息</param>
        /// <param name="equipmentInfo">设备信息</param>
        /// <param name="sellerInfo">销售商信息</param>
        /// <param name="nowTime">当前时间</param>
        /// <returns></returns>
        public static long AddInsuranceOrder(byte orderStatus, string createBy, InsuranceOrderInfoParam param, SellerInsuranceProductsInfo sellerInsuranceProductsInfo, CellPhoneServiceProductInfo insuranceProduct, EquipmentInfo equipmentInfo, ZBJF.Warranty.Model.Sellers sellerInfo, DateTime nowTime)
        {
            InsuranceOrder insuranceOrderModel = new InsuranceOrder();
            insuranceOrderModel.OrderStatus = orderStatus;//
            insuranceOrderModel.SellerInsuranceProductID = sellerInsuranceProductsInfo.SellerInsuranceProductsID;
            insuranceOrderModel.ThirdSaleEmployeeId = param.SaleEmployeeId;
            insuranceOrderModel.InsuranceProductID = insuranceProduct.ID;
            insuranceOrderModel.InsuranceCompany = sellerInsuranceProductsInfo.ParentInsuranceCompanyName; //承保公司
            insuranceOrderModel.InsuranceCompanyBranch = sellerInsuranceProductsInfo.InsuranceCompanyName; //承保公司分公司
            insuranceOrderModel.InsuranceCompanyID = sellerInsuranceProductsInfo.InsuranceCompanyID; //承保公司分公司
            insuranceOrderModel.ProductName = insuranceProduct.ProductName;
            insuranceOrderModel.LastModifyBy = createBy;
            insuranceOrderModel.LastModifyTime = nowTime;
            insuranceOrderModel.CreateBy = createBy;
            insuranceOrderModel.WaitDays = insuranceProduct.WaitDays;
            insuranceOrderModel.SellerBusinessNo = param.SellerBusinessNo;//第三方唯一编号
            insuranceOrderModel.OrderNO = CommonMethod.GetNewOrderNo();//工单号
            insuranceOrderModel.Price = 0;         //默认为0
            insuranceOrderModel.BuyType = (byte)InsuranceBuyType.NonActivationCodeBuy;//非激活购买
            insuranceOrderModel.UserName = param.UserName;//客户姓名
            insuranceOrderModel.UserPhone = param.UserPhone; //客户手机号码
            insuranceOrderModel.CertificateType = param.CertificateType; //证件类型 param.CertificateType
            insuranceOrderModel.CertificateNO = param.CertificateNO.Trim(); //证件号码
            insuranceOrderModel.CreateOrderTime = nowTime; //保单创建时间
            insuranceOrderModel.OrderFromType = (byte)InsuranceOrderFromType.HuaAnChiDu;
            insuranceOrderModel.SaleVendorId = sellerInfo.ID;//销售商户ID
            insuranceOrderModel.SaleVendorName = sellerInfo.SellersName.ToString();//销售商户名称
            insuranceOrderModel.PolicyPeriodYear = insuranceProduct.PolicyPeriodYear;
            insuranceOrderModel.PolicyPeriodMonth = insuranceProduct.PolicyPeriodMonth;
            insuranceOrderModel.PolicyPeriodDay = insuranceProduct.PolicyPeriodDay;
            insuranceOrderModel.InsuredAmount = insuranceProduct.InsuredAmount;//保额
            insuranceOrderModel.Price = sellerInsuranceProductsInfo.ZBJFSalePrice;
            insuranceOrderModel.SaleRetailPrice = sellerInsuranceProductsInfo.SaleRetailPrice;
            insuranceOrderModel.InsuranceCompanyRetailPrice = sellerInsuranceProductsInfo.InsuranceCompanyRetailPrice;
            return ServiceFactory.InsuranceOrderServiceInstance.AddEntities(insuranceOrderModel).ID;
        }
        #endregion

        #region 更新保险产品信息
        public bool UpdateInsuranceOrderInfo(InsuranceOrder insuranceOrderModel, byte orderStatus, long? sellerInsuranceProductsId, InsuranceOrderInfoParam param, CellPhoneServiceProductInfo insuranceProduct, SellerInsuranceProductsInfo sellerInsuranceProductsInfo, string createBy, DateTime nowTime)
        {
            insuranceOrderModel.OrderStatus = orderStatus;
            insuranceOrderModel.SellerInsuranceProductID = sellerInsuranceProductsId; //销售商产品ID
            insuranceOrderModel.ThirdSaleEmployeeId = param.SaleEmployeeId;    //第三方销售商员工ID
            insuranceOrderModel.InsuranceProductID = insuranceProduct.ID;
            insuranceOrderModel.InsuranceCompany = sellerInsuranceProductsInfo.ParentInsuranceCompanyName; //承保公司
            insuranceOrderModel.InsuranceCompanyBranch = sellerInsuranceProductsInfo.InsuranceCompanyName; //承保公司分公司
            insuranceOrderModel.InsuranceCompanyID = sellerInsuranceProductsInfo.InsuranceCompanyID; //承保公司分公司
            insuranceOrderModel.ProductName = insuranceProduct.ProductName;
            insuranceOrderModel.LastModifyBy = createBy;
            insuranceOrderModel.LastModifyTime = nowTime;
            insuranceOrderModel.SellerBusinessNo = param.SellerBusinessNo;//、、、
            insuranceOrderModel.WaitDays = insuranceProduct.WaitDays;
            insuranceOrderModel.Price = 0;         //默认为0
            insuranceOrderModel.BuyType = (byte)InsuranceBuyType.NonActivationCodeBuy;//非激活购买
            insuranceOrderModel.UserName = param.UserName;//客户姓名
            insuranceOrderModel.UserPhone = param.UserPhone; //客户手机号码
            insuranceOrderModel.CertificateType = param.CertificateType; //证件类型 param.CertificateType
            insuranceOrderModel.CertificateNO = param.CertificateNO.Trim(); //证件号码====================================================证件类型
            insuranceOrderModel.OrderFromType = (byte)InsuranceOrderFromType.HuaAnChiDu;
            insuranceOrderModel.PolicyPeriodYear = insuranceProduct.PolicyPeriodYear;
            insuranceOrderModel.PolicyPeriodMonth = insuranceProduct.PolicyPeriodMonth;
            insuranceOrderModel.PolicyPeriodDay = insuranceProduct.PolicyPeriodDay;
            insuranceOrderModel.InsuredAmount = insuranceProduct.InsuredAmount;//保额
            insuranceOrderModel.Price = sellerInsuranceProductsInfo.ZBJFSalePrice;
            insuranceOrderModel.SaleRetailPrice = sellerInsuranceProductsInfo.SaleRetailPrice;
            insuranceOrderModel.InsuranceCompanyRetailPrice = sellerInsuranceProductsInfo.InsuranceCompanyRetailPrice;

            return ServiceFactory.InsuranceOrderServiceInstance.UpdateEntities(insuranceOrderModel);
        }
        #endregion

        #region 更新服务项目 +  bool UpdateServiceProject(long insuranceOrderId,CellPhoneServiceProductInfo insuranceProduct , CellPhoneServiceProject cellPhoneServiceProjectInfo , EquipmentInfo equipmentInfo)
        private long UpdateServiceProject(long insuranceOrderId, string IMEI, string IDFV, CellPhoneServiceProductInfo insuranceProduct, CellPhoneServiceProject cellPhoneServiceProjectInfo, EquipmentInfo equipmentInfo)
        {
            //修改服务项目信息 —— 尺度默认只有一个手机维修服务项目
            CellPhoneInsuranceInfo cellPhone = ServiceFactory.CellPhoneInsuranceInfoServiceInstance.LoadEntities(t => t.InsuranceOrderID == insuranceOrderId).FirstOrDefault();
            if (cellPhone != null)
            {
                cellPhone.DeviceType = insuranceProduct.InsuranceDeviceType;
                cellPhone.ServiceProjectId = cellPhoneServiceProjectInfo.ServiceProjectId;
                cellPhone.ServiceProjectName = ServiceFactory.ServiceProjectServiceInstance.GetProjectName(cellPhoneServiceProjectInfo.ServiceProjectId);
                cellPhone.ServiceTimes = cellPhoneServiceProjectInfo.ServiceTimes;
                cellPhone.InsuredAmount = cellPhoneServiceProjectInfo.InsuredAmount;
                cellPhone.NewMachineInsuranceTimeLimit = cellPhoneServiceProjectInfo.NewMachineInsuranceTimeLimit;
                cellPhone.CellPhoneServiceProjectID = cellPhoneServiceProjectInfo.ID;
                cellPhone.ProductTypeId = equipmentInfo.ProductTypeId;  //设备类型ID
                cellPhone.ProductTypeName = equipmentInfo.ProductTypeName;//设备类型名称
                cellPhone.ProductBrandId = equipmentInfo.BrandId;  //品牌ID
                cellPhone.ProductBrandName = equipmentInfo.BrandName;//品牌名称
                cellPhone.ProductModelId = equipmentInfo.ModelId;  //型号ID
                cellPhone.ProductModelName = equipmentInfo.ModelName; //型号名称
                cellPhone.IMEI = IMEI;
                cellPhone.IDFV = IDFV;
                if (ServiceFactory.CellPhoneInsuranceInfoServiceInstance.UpdateEntities(cellPhone))
                {
                    return cellPhone.ID;
                }
            }
            return 0;
        }
        #endregion

        #region 更新服务项目 +  bool AddServiceProject(long insuranceOrderId,CellPhoneServiceProductInfo insuranceProduct , CellPhoneServiceProject cellPhoneServiceProjectInfo , EquipmentInfo equipmentInfo)
        private long AddServiceProject(long insuranceOrderId, string IMEI, string IDFV, CellPhoneServiceProductInfo insuranceProduct, CellPhoneServiceProject cellPhoneServiceProjectInfo, EquipmentInfo equipmentInfo)
        {
            //修改服务项目信息 —— 尺度默认只有一个手机维修服务项目
            CellPhoneInsuranceInfo cellPhone = new CellPhoneInsuranceInfo
            {
                InsuranceOrderID = insuranceOrderId,
                ServiceProjectId = cellPhoneServiceProjectInfo.ServiceProjectId,
                ServiceProjectName = ServiceFactory.ServiceProjectServiceInstance.GetProjectName(cellPhoneServiceProjectInfo.ServiceProjectId),
                ServiceTimes = cellPhoneServiceProjectInfo.ServiceTimes,
                DeviceType = insuranceProduct.InsuranceDeviceType,
                InsuredAmount = cellPhoneServiceProjectInfo.InsuredAmount,
            NewMachineInsuranceTimeLimit = cellPhoneServiceProjectInfo.NewMachineInsuranceTimeLimit,
                CellPhoneServiceProjectID = cellPhoneServiceProjectInfo.ID,
                ProductTypeId = equipmentInfo.ProductTypeId,  //设备类型ID
                ProductTypeName = equipmentInfo.ProductTypeName,//设备类型名称
                ProductBrandId = equipmentInfo.BrandId,  //品牌ID
                ProductBrandName = equipmentInfo.BrandName,//品牌名称
                ProductModelId = equipmentInfo.ModelId, //型号ID
                ProductModelName = equipmentInfo.ModelName, //型号名称
                IMEI = IMEI,
                IDFV = IDFV,
            };
            return ServiceFactory.CellPhoneInsuranceInfoServiceInstance.AddEntities(cellPhone).ID;
        }
        #endregion
    }
}